package com.wjl.shop.controller;

import com.wjl.shop.entity.Enclosure;
import com.wjl.shop.service.EnclosureService;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * 附件表(Enclosure)表控制层
 *
 * @author makejava
 * @since 2021-10-06 14:43:20
 */
@RestController
@RequestMapping("enclosure")
@CrossOrigin
public class EnclosureController {
    /**
     * 服务对象
     */
    @Resource
    private EnclosureService enclosureService;
    @Resource
    private HttpServletResponse response;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Enclosure selectOne(Integer id) {
        return this.enclosureService.queryById(id);
    }
    /**
     * 查询附件
     * */
    @GetMapping("selectFile")
    public Map<String, Object> selectFile(String orderCode){
        return  enclosureService.selectFile(orderCode);
    }

    @GetMapping(value = "showImg",produces = {MediaType.IMAGE_JPEG_VALUE,
            MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE})
    public void showImg(String name){
        OutputStream os = null;
        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());

            System.out.println(path);
            File upload = new File(path.getAbsoluteFile(), "upload");
            System.out.println(upload.getAbsolutePath());
            if (!upload.exists()) {
                upload.mkdirs();
            }
            File file = new File(upload, name);
            BufferedImage image=ImageIO.read(file);
            response.setContentType("image/png");
            os = response.getOutputStream();
            if(file.exists()){
                ImageIO.write(image,"jpg",os);

            }
        }catch (Exception e){
            e.getMessage();
        }

    }


}
